package spring.mvc.practice.controllers;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;

import spring.mvc.practice.*;




/**
 * Handles Create and Update of user account
 */
@Controller
public class AccountController {
	
	
	@Autowired
	private AccountDao accountDao;
		
	@Autowired
	private LovDao lovDao;
	
	@ModelAttribute
	public void populateModel(Model model) {
		model.addAttribute("states", lovDao.getLov("States") );
		model.addAttribute("countries", lovDao.getLov("Countries") );		
		model.addAttribute("gender",lovDao.getLov("Gender"));
	}
		
	
	private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
	


	@RequestMapping(value = "/create-account", method = RequestMethod.GET)
	public String createAccount(Model model,@ModelAttribute AccountBean accountBean) {
		logger.info("create account");
		

		
		return "tiles.create-account";
	}

	@RequestMapping(value = "/doCreateAccount", method = RequestMethod.POST)
	public String doCreateAccount(Model model,@Valid AccountBean accountBean, BindingResult result) {
		logger.info("do create account - " + accountBean.getFirst());

		if (result.hasErrors()) {
		  logger.info("error");
		  logger.info(accountBean.getGender());
		  accountBean.setCountry("US");
		  return "tiles.create-account";
		}
		else {				
		  accountBean.setRole("User");		
		  accountDao.save(accountBean);
		  return "tiles.home";
		}
/*		if (result.hasErrors())
		{
		  logger.info("error");
		  return "tiles.create-account";
		}*/
		
	}
	
	
	

	
	
}
